<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\AdminConfig;
use addons\qingdong\model\AttendanceRule;
use addons\qingdong\model\AttendanceStatisc;
use addons\qingdong\model\AttendanceTime;
use addons\qingdong\model\Message;
use addons\qingdong\model\Customer;
use addons\qingdong\model\Event;
use addons\qingdong\model\Staff;
use addons\qingdong\model\Leads;
use addons\qingdong\model\Attendance;
use think\Db;
use think\Exception;
use think\Log;
use think\Session;
use addons\qingdong\model\StaffDepartment;
use addons\qingdong\model\DingStaff;
use addons\qingdong\model\DingCustomer;
use addons\qingdong\model\DingContacts;
use addons\qingdong\model\DingRecord;
use addons\qingdong\library\Ding;

/**
 * 定时任务
 */
class Autotask extends \think\addons\Controller
{
    protected $noNeedLogin = ["*"];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        if (!$this->request->isCli()) {
            $this->error('只允许在终端进行操作!');
        }
    }

    /**
     * 合同
     */
    public function contract()
    {
        $endDate = date('Y-m-d', strtotime('+3 day'));
        $contracts = \addons\qingdong\model\Contract::where(['check_status' => 2, 'contract_status' => 0, 'end_time' => ['lt', $endDate]])->select();
        try {
            //合同即将到期通知
            foreach ($contracts as $v) {
                Message::addMessage(Message::CONTRACT_EXPIRE_TYPE, $v['id'], $v['owner_staff_id'], '');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        $this->plan();
        return 'success';
    }

    /**
     * 回款计划通知
     */
    public function plan()
    {
        $endDate = date('Y-m-d', strtotime('+1 day'));
        //进行中 -- 待回款
        $plans = \addons\qingdong\model\ReceivablesPlan::where(['status' => 0, 'remind_date' => ['lt', $endDate]])->select();

        try {
            //回款计划即将到期通知
            foreach ($plans as $v) {
                Message::addMessage(Message::PLAN_EXPIRE_TYPE, $v['contract_id'], $v['owner_staff_id'], '');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return 'success';
    }

    /**
     * 公海
     */
    public function seas()
    {

        if (AdminConfig::getConfigValue('auto', AdminConfig::TYPE_SEAS)) {//自动回收客户
            if (AdminConfig::getConfigValue('genjing', AdminConfig::TYPE_SEAS) == 1) {//未跟进客户回收
                $day = AdminConfig::getConfigValue('genjing_day', AdminConfig::TYPE_SEAS);
                $where = ['receivetime' => ['<', strtotime('-' . $day . ' day')]];
                if (AdminConfig::getConfigValue('genjing_success', AdminConfig::TYPE_SEAS) == 1) {
                    $where['contract_status'] = 0;
                }
                $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
                try {
                    foreach ($customers as $c) {
                        Customer::moveSeas($c['id']);
                        Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0);
                    }
                } catch (Exception $e) {
                    Log::error($e->getMessage());
                }
            }
            if (AdminConfig::getConfigValue('chengjiao', AdminConfig::TYPE_SEAS) == 1) {//未成交客户回收
                $day = AdminConfig::getConfigValue('chengjiao_day', AdminConfig::TYPE_SEAS);
                $where = [
                    'receivetime' => ['<', strtotime('-' . $day . ' day')],
                    'contract_status' => 0
                ];
                $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
                try {
                    foreach ($customers as $c) {
                        Customer::moveSeas($c['id']);
                        Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0);
                    }
                } catch (Exception $e) {
                    Log::error($e->getMessage());
                }
            }
        }

        return 'success';
    }

    /**
     * 日程提醒
     * @return string
     */
    public function event()
    {
        $endDate = date('Y-m-d H:i:s');
        $events = Event::where(['status' => 0, 'remind_time' => ['lt', $endDate]])->select();

        $endIds = Event::where([
            'status' => ['in', [0, 1]],
            'auto_end' => 1,
            'end_time' => ['lt', $endDate]
        ])->column('id');

        try {
            //日程自动结束
            Event::where(['id' => ['in', $endIds]])->update(['status' => 2]);

            //日程时间提醒
            foreach ($events as $v) {
                if (Message::where([
                    'relation_type' => Message::EVENT_TYPE,
                    'relation_id' => $v['id'],
                    'to_staff_id' => $v['staff_id']
                ])->count()) {
                    //已经提醒过了
                    continue;
                }
                Message::addMessage(Message::EVENT_TYPE, $v['id'], $v['staff_id'], 0);
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        return 'success';
    }

    /**
     * 打卡定时任务
     */
    public function attendance()
    {
        $w = date('w');
        $date = [
            1 => 'monday',
            2 => 'tuesday',
            3 => 'wednesday',
            4 => 'thursday',
            5 => 'friday',
            6 => 'saturday',
            0 => 'weekday',
        ];
        $weekname = $date[$w];
        $times = AttendanceTime::where([$weekname => 1])->select();
        if (empty($times)) {
            return '未设置规则';
        }
        $row = AttendanceStatisc::where(['time' => date('Y-m-d')])->find();
        if (!empty($row)) {
            return '规则已生成';
        }
        $times = collection($times)->toArray();
        $rule = AttendanceRule::where([])->find();

        $statiscs = AttendanceStatisc::where(['time' => date('Y-m-d', strtotime('-1 day'))])->select();
        foreach ($statiscs as $v) {
            $update = [];
            if (empty($t['clock_in']) && !empty($t['clock_out'])) {//缺卡
                $update['clock_in_status'] = 1;
            }
            if (empty($t['clock_out']) && !empty($t['clock_in'])) {//缺卡
                $update['clock_out_status'] = 1;
            }
            if (empty($t['clock_in']) && empty($t['clock_out'])) {//旷工
                $update['clock_in_status'] = 2;
                $update['clock_out_status'] = 2;
            }
            if ($update) {
                $statiscModel = new AttendanceStatisc();
                $statiscModel->save($update, ['id' => $v['id']]);
            }

        }
        $staff_ids = explode(',', $rule['staff_id']);

        $statisc = [];
        foreach ($staff_ids as $sid) {
            foreach ($times as $t) {
                $statisc[] = [
                    'staff_id' => $sid,
                    'number' => $t['number'],
                    'time' => date('Y-m-d'),
                    'start_time' => $t['start_time'],
                    'end_time' => $t['end_time'],
                    'ustart_time' => $t['ustart_time'],
                    'uend_time' => $t['uend_time'],
                    'dstart_time' => $t['dstart_time'],
                    'dend_time' => $t['dend_time'],
                    'start_status' => $t['start_status'],
                    'end_status' => $t['end_status'],
                ];
            }
        }
        $statiscModel = new AttendanceStatisc();
        $result = $statiscModel->allowField(true)->saveAll($statisc);
        if (empty($result)) {
            return '生成规则失败';
        }
        return '生成规则成功';
    }

    /*
     * 线索池分配
     */
    public function leadpool(){
        if(AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD)){
            $leadauto = AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD);
            $lead_day = AdminConfig::getConfigValue('lead_day', AdminConfig::TYPE_LEAD);
            $attendance = AdminConfig::getConfigValue('leadcard', AdminConfig::TYPE_LEAD);
            $department = AdminConfig::getConfigValue('department', AdminConfig::TYPE_LEAD);

            //开启分配
            if($leadauto == 1 && $lead_day>0 && $department){
                $leadpool = Leads::where('owner_staff_id is null or owner_staff_id = 0')->order('id desc')->limit(100)->column('id');
               if($leadpool){
                   $department = explode(',',$department);
                   $staffinfo = array();
                   foreach($department as $k=>$v){
                       $staffids = Staff::where('', 'exp', Db::raw('FIND_IN_SET(' . $v . ',group_ids)'))->where(['status'=>1])->column('id');
                       $staffinfo[] = $staffids;
                   }
                   if(!$staffinfo){
                       return '无数据';
                   }
                   $staffinfos =[];
                   foreach($staffinfo as $k=>$v){
                       foreach($v as $ks=>$vs){
                           $staffinfos[] = $vs;
                       }
                   }
                   $staff = array_unique($staffinfos);
                   foreach($leadpool as $ks=>$vs){
                       $stafflead =[];
                       foreach($staff as $k=>$v){
                           if($attendance == 1){ //打卡
                               $whereC['staff_id']= $v;
                               $whereC['createtime'] = array(array('egt',strtotime(date('Y-m-d 00:00:00'))),array('elt',strtotime(date('Y-m-d 23:59:59'))));
                               $leadcard = Attendance::where($whereC)->find();
                               if(!$leadcard){//未打卡不分配
                                   continue;
                               }
                           }
                           $wherelead['owner_staff_id'] = $v;
                           $wherelead['receive_time'] = array(array('egt',strtotime('-'.$lead_day.' days',time())),array('elt',time()));
                           $lead = Leads::where($wherelead)->count();
                           $stafflead[] = array(
                               'id'=>$v,
                               'num'=>$lead
                           );
                       }
                       if($stafflead){
                           $num_count = array_column($stafflead,'num');//返回数组中指定的一列
                           array_multisort($num_count,SORT_ASC,$stafflead);
                           Leads::where(array('id'=>$vs))->update(array('owner_staff_id'=>$stafflead[0]['id'],'receive_time'=>time()));
                       }
                   }

               }

            }
        }
        return 'success';
    }

    /**
     * 钉钉批量获取客户
     */
    public function dingcustomer(){
        date_default_timezone_set('Asia/Shanghai');
        $ding=new Ding();
        //获取access_token
        $token = $ding->getAccessToken();
        if($token->errcode != 0){
            $this->error($token->errmsg);
        }
        $ding=new Ding();
        $accessToken = $token->access_token;
        $DingStaff = DingStaff::where(array('type'=>0))->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }

        foreach($DingStaff as $k=>$v){
            if(Session::get($v['user_id']."dingcustomer")){
                $startnum = intval(Session::get($v['user_id']."dingcustomer")/2-1);
                $endnum = Session::get($v['user_id']."dingcustomer");
            }else{
                $startnum = 0;
                $endnum =100;
            }
            $customer = $ding->customerBatch($accessToken,$v['user_id'],$startnum,$endnum);

            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingCustomer::where(array('instance_id'=>$vs->instance_id,'type'=>0))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $instance_id = $vs->instance_id;
                $customers = isset($data['customer_name']) ? $data['customer_name'] : '';
                $adressinfo = isset($data['address']['extendValue']) ? json_decode($data['address']['extendValue'],true) : '';
                $address_detail = '';
                $address = '';
                if($adressinfo){
                    $province = isset($adressinfo['province']['name']) ? $adressinfo['province']['name'] : '';
                    $city  = isset($adressinfo['city']['name']) ? $adressinfo['city']['name'] : '';
                    $district  = isset($adressinfo['district']['name']) ? $adressinfo['district']['name'] : '';
                    $address_detail  = isset($adressinfo['detail']['name']) ? $adressinfo['detail']['name'] : '';
                    $address = $province.$city.$district;
                }
                $remark = isset($data['TextareaField-K55CWZ2E']) ? $data['TextareaField-K55CWZ2E'] : '';
                $source = isset($data['DDSelectField-K2U5GX3B']['value']) ? $data['DDSelectField-K2U5GX3B']['value'] : '';
                $owner_staff_id=$vs->permission->owner_userid_list[0];
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'user_id'=>$create_staff_id,
                    'name'=>$customers,
                    'address'=>$address,
                    'address_detail'=>$address_detail,
                    'source'=>$source,
                    'remark'=>$remark,
                    'owner_staff_id'=>$owner_staff_id,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingCustomer::create($customerData);
            }


            if(Session::get($v['user_id']."dingcustomer")){
                Session::set($v['user_id']."dingcustomer", 100*2);
            }else{
                Session::set($v['user_id']."dingcustomer", 100);
            }

        }
        $this->success('同步成功');

    }
    /**
     * 钉钉批量获取联系人
     */
    public function dingcontacts(){
        date_default_timezone_set('Asia/Shanghai');
        $ding=new Ding();
        //获取access_token
        $token = $ding->getAccessToken();
        if($token->errcode != 0){
            $this->error($token->errmsg);
        }
        $ding=new Ding();
        $accessToken = $token->access_token;
        $DingStaff = DingStaff::where(array('type'=>0))->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        foreach($DingStaff as $k=>$v){
            if(Session::get($v['user_id']."dingcontacts")){
                $startnum = intval(Session::get($v['user_id']."dingcontacts")/2-1);
                $endnum = Session::get($v['user_id']."dingcontacts");
            }else{
                $startnum = 0;
                $endnum =100;
            }
            $customer = $ding->contactsBatch($accessToken,$v['user_id'],$startnum,$endnum);
            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingContacts::where(array('instance_id'=>$vs->instance_id))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $contact_related_customer = json_decode($data['contact_related_customer']['extendValue'],true);
                $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
                if(!$instanceId){
                    continue;
                }
                $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
                if(!$customerId){
                    continue;
                }
                $instance_id = $vs->instance_id;
                $contact_name = isset($data['contact_name']) ? $data['contact_name'] : '';
                $post = isset($data['contact_position']['extendValue']) ? json_decode($data['contact_position']['extendValue'],true)[0]['label'] : '';
                $email = isset($data['TextField-K55DPXC9']) ? $data['TextField-K55DPXC9'] : '';
                $mobile = isset($data['contact_phone']['value']) ? $data['contact_phone']['value'] : '';
                $remark = isset($data['TextareaField-K2UG1B59']) ? $data['TextareaField-K2UG1B59'] : '';
                $owner_staff_id=$vs->permission->owner_userid_list[0];
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'customer_id'=>$customerId,
                    'name'=>$contact_name,
                    'post'=>$post,
                    'email'=>$email,
                    'mobile'=>$mobile,
                    'remarks'=>$remark,
                    'owner_staff_id'=>$owner_staff_id,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingContacts::create($customerData);
            }

            if(Session::get($v['user_id']."dingcontacts")){
                Session::set($v['user_id']."dingcontacts", 100*2);
            }else{
                Session::set($v['user_id']."dingcontacts", 100);
            }

        }
        $this->success('同步成功');
    }
    /**
     * 钉钉批量获取跟进记录
     */
    public function dingrecord(){

        date_default_timezone_set('Asia/Shanghai');
        $ding=new Ding();
        //获取access_token
        $token = $ding->getAccessToken();
        if($token->errcode != 0){
            $this->error($token->errmsg);
        }
        $ding=new Ding();
        $accessToken = $token->access_token;

        $DingStaff = DingStaff::select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        foreach($DingStaff as $k=>$v){
            if(Session::get($v['user_id']."dingrecord")){
                $startnum = intval(Session::get($v['user_id']."dingrecord")/2-1);
                $endnum = Session::get($v['user_id']."dingrecord");
            }else{
                $startnum = 0;
                $endnum =100;
            }
            $customer = $ding->recordBatch($accessToken,$v['user_id'],$startnum,$endnum);
            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingRecord::where(array('instance_id'=>$vs->instance_id))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $contact_related_customer = json_decode($data['follow_record_related_customer']['extendValue'],true);
                $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
                if(!$instanceId){
                    continue;
                }
                $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
                if(!$customerId){
                    continue;
                }
                $instance_id = $vs->instance_id;
                $content = isset($data['TextareaField-K2U5UJAF']) ? $data['TextareaField-K2U5UJAF'] : '';
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'customer_id'=>$customerId,
                    'content'=>$content,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingRecord::create($customerData);
            }
            if(Session::get($v['user_id']."dingrecord")){
                Session::set($v['user_id']."dingrecord", 100*2);
            }else{
                Session::set($v['user_id']."dingrecord", 100);
            }
        }
        $this->success('同步成功');
    }

    /**
     * 企业微信批量获取客户
     */
    public function wxcustomer(){
        $this->corpid =AdminConfig::where(array('field'=>'corpid'))->value('value');
        $corpsecret=AdminConfig::where(array('field'=>'corpsecret'))->value('value');
        $url ='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$this->corpid.'&corpsecret='.$corpsecret;
        $token = $this->http_get($url);
        $token = json_decode($token,true);
        if($token['errcode'] != 0){
            $this->error($token['errmsg']);
        }

        $DingStaff = DingStaff::where(array('type'=>1))->limit(100)->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        $staffUser = array();
        foreach($DingStaff as $k=>$v){
            $staffUser[] = $v['user_id'];
        }
        $user = array(
            'userid_list'=>$staffUser,
            'cursor'=>Session::get("wxcustomer"),
            'limit'=>100
        );
        $url ='https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token='.$token['access_token'];
        $customer = $this->http_post($url,json_encode($user));
        $customer = json_decode($customer,true);
        if($customer['errcode'] != 0){
            $this->error($customer['errmsg']);
        }
        Session::set("wxcustomer", $customer['next_cursor']);
        foreach($customer['external_contact_list'] as $ks=>$vs){
            $customerFind = DingCustomer::where(array('instance_id'=>$vs['external_contact']['external_userid']))->find();
            if($customerFind){
                continue;
            }
            $data = $vs;
            $instance_id = isset($data['external_contact']['external_userid']) ? $data['external_contact']['external_userid'] : '';
            $customerName = isset($data['external_contact']['name']) ? addslashes(filter_Emoji($data['external_contact']['name'])) : '';
            $owner_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
            $create_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
            $createtime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';
            $updatetime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';

            $customerData = array(
                'type' => 1,
                'instance_id'=>$instance_id,
                'user_id'=>$create_staff_id,
                'name'=>$customerName,
                'owner_staff_id'=>$owner_staff_id,
                'create_staff_id'=>$create_staff_id,
                'createtime'=>$createtime,
                'updatetime'=>$updatetime,
            );
            $customers = DingCustomer::create($customerData);
            $customerId = DingCustomer::getLastInsID();
            //同步联系人
            $contactFind = DingContacts::where(array('instance_id'=>$instance_id))->find();
            if($contactFind){
                DingContacts::where(array('id'=>$contactFind['id']))->update(array('customer_id' =>$customerId));
                continue;
            }
            $contactData = array(
                'type' =>1,
                'instance_id' =>$instance_id,
                'customer_id' =>$customerId,
                'name' =>$customerName,
                'mobile' =>isset($data['follow_info']['remark_mobiles'][0]) ? $data['follow_info']['remark_mobiles'][0] : '',
                'create_staff_id' =>$owner_staff_id,
                'owner_staff_id' =>$create_staff_id,
            );
            DingContacts::create($contactData);
        }

        $this->success('同步成功');

    }
    /**
     * curl请求
     */
    private function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
    /**
     * curl请求
     */
    private function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

}
